//
//  CaipuViewController.m
//  KCZ_B段项目
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 Sky. All rights reserved.
//

#import "CaipuViewController.h"
#import "FitHeader.h"
#import "KYLikeCollectionCell.h"
#import "KYCaipuFirstCollectionCell.h"
#import "KYcpLikeCollectionCell2.h"
#import "HTTPMethod.h"
#import "changeString.h"
#import "MyScrollView.h"
#import "ZJHCaiPuScrollViewModel.h"
#import "ZJHCaipuClassifyModel.h"
#import "ZJHCaipuLikeModel.h"
#import <UIImageView+WebCache.h>
#import "FontSizeSingleTon.h"
#define Font [[FontSizeSingleTon shareFontSize]array]
#import "ZJHCaipuCollectionReusableView.h"
#import "ShakeViewController.h"
#import "CaiPuXinShouViewController.h"
#import "CaiPuRenQiViewController.h"
#import <MBProgressHUD.h>
#import "ZJHShakeCaipuViewController.h"
#import "ZJHShakeModel.h"
#import "CaiPuLikeMoreViewController.h"
#import "CaipuLikeClassifyViewController.h"
#import "CaiPuClassifyViewController.h"
#import "VideoListViewController.h"
#import "CaiPuNearbyViewController.h"
//引入百度地图头文件
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
@interface CaipuViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout, ScrollViewSelectDelegate, BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate>
@property(nonatomic, strong)UICollectionView *collectionview;
@property(nonatomic, strong)NSMutableArray *dataSourceArray;
@property(nonatomic, strong)UIView *headerView;
@property(nonatomic, strong)MyScrollView *headerScrollView;
@property(nonatomic, strong)NSMutableArray *scrollDataArray;
@property(nonatomic, strong)NSMutableArray *classifyArray;
@property(nonatomic, strong)NSMutableArray *likeDataArray;
@property(nonatomic, strong)MBProgressHUD *progressView;
@property(nonatomic, strong)BMKLocationService *locService;
@property(nonatomic, strong)BMKGeoCodeSearch *search;
@end

@implementation CaipuViewController

#pragma mark 点击scrollView跳转方法
-(void)scrollViewPushToViewWithReceipId:(NSInteger)receipId Title:(NSString *)title
{
    ZJHShakeModel *model = [[ZJHShakeModel alloc]init];
    ZJHShakeCaipuViewController *VC = [[ZJHShakeCaipuViewController alloc]init];
    model.RecipeId = receipId;
    model.Title = title;
    VC.tempModel = model;
    [self.navigationController pushViewController:VC animated:YES];
}
#pragma mark 点击scrollView跳转视频界面
-(void)scrollViewPushToVideoViewWithReceipId:(NSString *)idString
{
    VideoListViewController *videoVC = [[VideoListViewController alloc]init];
    videoVC.IdString = idString;
    [self.navigationController pushViewController:videoVC animated:YES];
}
- (void)viewDidLoad {
    //这是首页
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"菜谱";
    self.navigationController.navigationBar.translucent = NO;
//    [self createProgressView];
    [self GetClassifyData];
    [self getHomePageData];
    
}
-(void)loadView
{
    [super loadView];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(64 * wt, 64 * ht);
    flowLayout.minimumLineSpacing = 5 * ht;
    flowLayout.minimumInteritemSpacing = 10 * wt;
    flowLayout.sectionInset = UIEdgeInsetsMake(25 * ht, 5 * wt, 5 * ht, 5* wt);
    flowLayout.headerReferenceSize = CGSizeMake(0, 100 * ht);
    //滚动方向
    //  flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //整页滚动
    _collectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 104) collectionViewLayout:flowLayout];
    _collectionview.delegate =self;
    _collectionview.dataSource = self;
    _collectionview.backgroundColor = [UIColor whiteColor];
//    _collectionview.pagingEnabled = YES;
    [self.view addSubview:_collectionview];
    
    // 重点 collectionView 注册cell
    //第一个自定义cell厨房宝典等
    [_collectionview registerClass:[KYCaipuFirstCollectionCell class] forCellWithReuseIdentifier:@"identifier1"];//重用
    //第二个自定义cell猜你喜欢的文字部分cell
    [_collectionview registerClass:[KYLikeCollectionCell class] forCellWithReuseIdentifier:@"identifier2"];
    [_collectionview registerClass:[KYcpLikeCollectionCell2 class] forCellWithReuseIdentifier:@"identifier3"];
    //sectionTitle
    [_collectionview registerClass:[ZJHCaipuCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"identifier4"];
    //顶视图
    _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 250 * ht)];
    _headerView.backgroundColor = [UIColor magentaColor];
    [_collectionview addSubview:_headerView];
    [self createProgressView];
}
//创建progressView
-(void)createProgressView
{
    _progressView = [[MBProgressHUD alloc]initWithView:_collectionview];
    _progressView.labelText = @"加载中...";
    _progressView.backgroundColor = [UIColor whiteColor];
    [_progressView setMode:MBProgressHUDModeIndeterminate];
    [_collectionview addSubview:_progressView];
    [_progressView show:YES];
}
#pragma mark 解析首页数据
-(void)getHomePageData
{
    
    NSString *POSTString = @"http://api.haodou.com/index.php?appid=2&appkey=9ef269eec4f7a9d07c73952d06b5413f&format=json&sessionid=1446287334198&vc=77&vn=5.4.0&loguid=0&deviceid=haodou359786058377939&uuid=087c7496ab334bd9babe6eb99709c4f8&channel=baidu_v540&method=Index.index&virtual=&signmethod=md5&v=2&timestamp=1446287343&nonce=0.5697249621598149&appsign=dba820543f12b6ea4fc06c595924b118";
    NSString *body = @"limit=10&sign=&uid=0&uuid=087c7496ab334bd9babe6eb99709c4f8&offset=0";
    _scrollDataArray = [NSMutableArray array];
    _likeDataArray = [NSMutableArray array];
    [HTTPMethod getDataByString:POSTString BodyDic:[changeString changeStringToDictionary:body] WithDataBlock:^(id data) {

        NSDictionary *allDic = [data objectForKey:@"result"];
#pragma mark 滚动视图数据
        
        NSDictionary *recipeDic = [allDic objectForKey:@"recipe"];
        NSArray *scrollViewArray = [recipeDic objectForKey:@"list"];
        for (NSDictionary *dic in scrollViewArray) {
            
            NSString *str = [dic objectForKey:@"Url"];
            if ([str hasSuffix:@"video=0"] || [str hasSuffix:@"video=1"]) {
                ZJHCaiPuScrollViewModel *scrollModel = [[ZJHCaiPuScrollViewModel alloc]init];
                [scrollModel setValuesForKeysWithDictionary:dic];
                [_scrollDataArray addObject:scrollModel];
                
            }
        }
        //创建pageControll
        UIPageControl *pageControll = [[UIPageControl alloc]initWithFrame:CGRectMake(100 * wt, 230 * ht, 175 * wt, 10 * ht)];
        _headerScrollView = [[MyScrollView alloc]initWithFrame:_headerView.frame imageArray:_scrollDataArray pageC:pageControll];
        _headerScrollView.myDelegate = self;
        [_headerView addSubview:_headerScrollView];
        [_headerView addSubview:pageControll];
#pragma mark 猜你喜欢数据
        NSDictionary *personDic = [allDic objectForKey:@"person"];
        //不带图tag数组
        NSArray *tagArray = [personDic objectForKey:@"tag"];
        //带图list数组
        NSArray *listArray = [personDic objectForKey:@"list"];
        for (NSDictionary *dic1 in listArray) {
            ZJHCaipuLikeModel *likeModel = [[ZJHCaipuLikeModel alloc]init];
            [likeModel setValuesForKeysWithDictionary:dic1];
            [_likeDataArray addObject:likeModel];
        }
        for (NSDictionary *dic2 in tagArray) {
            ZJHCaipuLikeModel *likeModell = [[ZJHCaipuLikeModel alloc]init];
            [likeModell setValuesForKeysWithDictionary:dic2];
            [_likeDataArray addObject:likeModell];
        }
        [_collectionview reloadData];
        [_progressView removeFromSuperview];
    }];
    
}

#pragma mark 解析分类数据
-(void)GetClassifyData
{
    
    _classifyArray = [NSMutableArray array];
    NSString *postString = @"http://api.haodou.com/index.php?appid=4&appkey=573bbd2fbd1a6bac082ff4727d952ba3&appsign=01942abebb7868855117814c87eb6b60&channel=appstore&deviceid=0f607264fc6318a92b9e13c65db7cd3c%7CCC2D6423-97F6-437A-B8DE-CBB86A71C6F1%7C608CBAFB-426B-4C02-96CA-F5B029C17D76&format=json&loguid=&method=Search.getcatelist&nonce=1446599376&sessionid=1446599236&signmethod=md5&timestamp=1446599376&uuid=f54ccedd4a37e51b4340c5dc18fe353c&v=2&vc=43&vn=v5.4.0";
    NSString *bodyString = @"sign=&uid=&uuid=f54ccedd4a37e51b4340c5dc18fe353c";
    [HTTPMethod getDataByString:postString BodyDic:[changeString changeStringToDictionary:bodyString] WithDataBlock:^(id data) {

            NSDictionary *dataDic = [data objectForKey:@"result"];
            NSArray *array = [dataDic objectForKey:@"list"];
            
            for (NSDictionary *dic in array) {
             ZJHCaipuClassifyModel *model = [[ZJHCaipuClassifyModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [_classifyArray addObject:model];
                
            }
        [_collectionview reloadData];
    }];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 4;
    }
    else if (section == 1)     //这是每个section有几个cell
    {
        return 11;
    }
    return _classifyArray.count;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    if (section == 0) {
        return 25 * wt;
    }
    if (section == 1) {       //这是最小列间距
        return 8 * wt;
    }
    return 25 * wt;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    if (section == 2) {      //这是每个section中的最小行间距
        return 45 * ht;
    }
    return 10 * ht;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(64 * wt, 100 * ht);
    }
    if (indexPath.section == 1) {      //这个方法是每个cell的大小
        if (indexPath.row < 3) {
            return CGSizeMake(115 * wt, 120 * ht);
        }
        return CGSizeMake((375 - 35) * wt / 4, 30 * ht);
    }

    return CGSizeMake(64 * wt, 100 * ht);
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        //直接进重用池
        KYCaipuFirstCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier1" forIndexPath:indexPath];
        switch (indexPath.row) {
            case 0:
                cell.typeImage.image = [UIImage imageNamed:@"xinshou"];
                cell.titleLabel.text = @"新手入门";
                break;
            case 1:
                cell.typeImage.image = [UIImage imageNamed:@"renqi"];
                cell.titleLabel.text = @"人气食谱";
                break;
            case 2:
                cell.typeImage.image = [UIImage imageNamed:@"fujin"];
                cell.titleLabel.text = @"附近";
                break;
            case 3:
                cell.typeImage.image = [UIImage imageNamed:@"shake"];
                cell.titleLabel.text = @"摇一摇";
                break;
            default:
                break;
        }
       
         return cell;
    }
   
    
   else if (indexPath.section == 1) {
       
        if (indexPath.row < 3) {
            KYcpLikeCollectionCell2 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier3" forIndexPath:indexPath];
            if (_likeDataArray.count != 0) {
                ZJHCaipuLikeModel *likeModel = _likeDataArray[indexPath.row];
                [cell.cookImage sd_setImageWithURL:[NSURL URLWithString:likeModel.Img]];
                cell.titleLabel.text = likeModel.Title;
            }
            
            return cell;
        }
        KYLikeCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier2" forIndexPath:indexPath];
       if (_likeDataArray.count != 0) {
           ZJHCaipuLikeModel *likeModel = _likeDataArray[indexPath.row];
           [cell.xinImage sd_setImageWithURL:[NSURL URLWithString:likeModel.Img]];
           cell.titleLabel.text = likeModel.Title;
       }
        return cell;
    }
  else
  {
      KYCaipuFirstCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier1" forIndexPath:indexPath];
      if (_classifyArray.count != 0) {
          ZJHCaipuClassifyModel *model = _classifyArray[indexPath.row];
          cell.titleLabel.text = model.Cate;
          [cell.typeImage sd_setImageWithURL:[NSURL URLWithString:model.ImgUrl]];
      }
      
      return cell;
  }
   
    
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    ZJHCaipuCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"identifier4" forIndexPath:indexPath];
    switch (indexPath.section) {
        case 1:
        {
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
            headerView.userInteractionEnabled = YES;
            [headerView addGestureRecognizer:tap];
            headerView.titleLable.text = @"猜你喜欢";
            UILabel *moreLable = [[UILabel alloc]initWithFrame:CGRectMake(305 * wt, 20 * ht, 50 * wt, 20 * ht)];
            moreLable.text = @"更多>>";
            moreLable.font = [UIFont systemFontOfSize:[Font[1] integerValue]];
            [headerView addSubview:moreLable];
        }
            break;
        case 2:
            headerView.titleLable.text = @"分类";
            break;
        default:
            break;
    }
    return headerView;

}
#pragma mark 猜你喜欢手势方法
-(void)tapAction
{
    CaiPuLikeMoreViewController *moreVC = [[CaiPuLikeMoreViewController alloc]init];
    [self.navigationController pushViewController:moreVC animated:YES];
}
//分区数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 3;
}
//headerview的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(SCREENWIDTH, 250 * ht);
    }
    else
    {
        return CGSizeMake(SCREENWIDTH, 40 * ht);
    }
}

//navigationcontroller渐变透明方法
//-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
//{
//    if ( scrollView == _collectionview) {
//        
//    CGFloat alpha = scrollView.contentOffset.y / 200;
//    if (alpha < 0) {
//        alpha = 0;
//    }
//    else if (alpha > 1)
//    {
//        alpha = 1;
//    }
//    
//    self.navigationController.navigationBar.alpha = alpha;
//    }
//}

#pragma mark cell点击方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                {
                    CaiPuXinShouViewController *xinshouVC = [[CaiPuXinShouViewController alloc]init];
                    [xinshouVC setHidesBottomBarWhenPushed:YES];
                    [self.navigationController pushViewController:xinshouVC animated:YES];
                }
                    break;
                case 1:
                {
                    CaiPuRenQiViewController *renQiVC = [[CaiPuRenQiViewController alloc]init];
                    [renQiVC setHidesBottomBarWhenPushed:YES];
                    [self.navigationController pushViewController:renQiVC animated:YES];
                }
                    break;
                case 2:
                {
//                    CaiPuNearbyViewController *nearbyVC = [[CaiPuNearbyViewController alloc]init];
//                    [nearbyVC setHidesBottomBarWhenPushed:YES];
//                    [self.navigationController pushViewController:nearbyVC animated:YES];
                    [self locate];
                }
                    break;
                case 3:
                {
                    ShakeViewController *shakeVC = [[ShakeViewController alloc]init];
                    [shakeVC setHidesBottomBarWhenPushed:YES];
                    [self.navigationController pushViewController:shakeVC animated:YES];
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
         case 1:
        {
            if (indexPath.row < 3) {
                ZJHCaipuLikeModel *likeModel = _likeDataArray[indexPath.row];
                NSString *str1 = likeModel.Url;
                NSArray *array1 = [str1 componentsSeparatedByString:@"id="];
                NSString *str2 = array1[1];
                NSArray *array2 = [str2 componentsSeparatedByString:@"&"];
                NSString *string = array2[0];
                NSInteger receipId = [string integerValue];
                ZJHShakeModel *model = [[ZJHShakeModel alloc]init];
                ZJHShakeCaipuViewController *VC = [[ZJHShakeCaipuViewController alloc]init];
                model.RecipeId = receipId;
                model.Title = likeModel.Title;
                VC.tempModel = model;
                [self.navigationController pushViewController:VC animated:YES];
            }
            else
            {
                CaipuLikeClassifyViewController *likeClassifyVC = [[CaipuLikeClassifyViewController alloc]init];
                likeClassifyVC.tempModel = _likeDataArray[indexPath.row];
                [self.navigationController pushViewController:likeClassifyVC animated:YES];
            }
        }
            break;
        case 2:
        {
            CaiPuClassifyViewController *classifyVC = [[CaiPuClassifyViewController alloc]init];
            classifyVC.tempModel = _classifyArray[indexPath.row];
            [self.navigationController pushViewController:classifyVC animated:YES];
        }
            break;
        default:
            break;
    }
}
#pragma mark 定位
-(void)locate
{
    _search = [[BMKGeoCodeSearch alloc]init];
    _locService = [[BMKLocationService alloc]init];
#pragma mark 开始定位
    [_locService startUserLocationService];
    _locService.delegate = self;
    
    _search.delegate = self;
}
#pragma mark 用户位置更新,调用方法
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    CGFloat lat = userLocation.location.coordinate.latitude;
    CGFloat lon = userLocation.location.coordinate.longitude;
    BMKOpenPoiNearbyOption *option = [[BMKOpenPoiNearbyOption alloc]init];
    option.appScheme = @"baidumapsdk://mapsdk.baidu.com";
    option.keyword = @"美食";
    option.location = CLLocationCoordinate2DMake(lat, lon);
    //周边距离半径
    option.radius = 1000;
    BMKOpenErrorCode code = [BMKOpenPoi openBaiduMapPoiNearbySearch:option];
    _locService.delegate = nil;
    _search.delegate = nil;
}
//-(void)viewWillDisappear:(BOOL)animated
//{
//    self.navigationController.navigationBar.alpha = 1.0;
//    self.navigationController.navigationBar.translucent = NO;
//}
-(void)viewWillAppear:(BOOL)animated
{
//    self.navigationController.navigationBar.alpha = 1;
    self.navigationController.navigationBar.translucent = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
